<?php

namespace App\Admin\Controller\Cms;

class Hotword extends \App\Admin\Controller\Authed {

    public function index() {

        $do = $this->request->get('do');

        if ($do == 'sort') {
            $sorts = $this->request->getPost('sorts');

            foreach ($sorts as $key => $value) {
                $result = Cms()->Hotword()->setSort($key, $value);

                if (!$result) {
                    fail();
                }
            }

            succ();
        }

        $rows = Cms()->Hotword()->getAll();

        foreach ($rows as &$row) {
            $row['state_title'] = Cms()->Hotword()->getStateAssoc($row['state']);
        }
        unset($row);

        $this->rows = $rows;
    }

    public function edit() {
        
        $this->enablePageCache(true);

        $id = intval($this->request->get('id'));

        if ($this->request->isPost()) {

            $data = $this->request->get();

            if ($id) {
                $result = Cms()->Hotword()->update($id, $data);
                if ($result) {
                    succ('', '', 2);
                } else {
                    fail();
                }
            } else {
                $result = Cms()->Hotword()->add($data);
                if ($result) {
                    succ('', '', 2);
                } else {
                    fail();
                }
            }
        }

        $this->detail = Cms()->Hotword()->get($id);

        $this->states = Cms()->Hotword()->getStateAssoc();
    }

    public function remove() {

        $id = intval($this->request->get('id'));

        $result = Cms()->Hotword()->remove($id);

        if ($result) {
            succ();
        } else {
            fail();
        }
    }

}
